import { fileURLToPath, URL } from 'node:url'
import { loadEnv } from 'vite'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs';
import poscssPresetEnv from 'postcss-preset-env';
import { visualizer } from "rollup-plugin-visualizer";
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
const HOST = 'http://192.168.0.161' // 开发环境
// const HOST = 'http://192.168.0.162' // 测试环境
//const HOST = 'https://razermatrix.ngpcloud.com/' // 生产环境



function updateVersion() {
  return {
    name: 'updateVersion',
    buildStart() {
      const versionData = { version: new Date().getTime() };
      fs.writeFileSync('public/version.json', JSON.stringify(versionData));
    }
  };
}


export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const { VITE_APP_TITLE } = env
  return {
    plugins: [
      vue(),
      // 自动导入 Vue API
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          'pinia',
          {
            'ant-design-vue': [
              // 直接导出的方法
              'message',
              'notification',
              'Modal'
            ]
          }
        ],
        dts: true, // 生成 auto-imports.d.ts
        eslintrc: {
          enabled: true, // 生成 .eslintrc-auto-import.json
        },
      }),
      // 自动导入组件
      Components({
        resolvers: [
          // 自动导入 Ant Design Vue 组件
          AntDesignVueResolver({
            importStyle: false, // css in js
          }),
        ],
        dts: true, // 生成 components.d.ts
      }),
      VITE_APP_TITLE === 'prod' ? updateVersion() : false, // 更新版本号
      // 打包分析
      // visualizer({
      //   gzipSize: true,
      //   brotliSize: true,
      //   emitFile: false,
      //   filename: "test.html",
      //   open: true
      // }),
    ],
    css: {
      loaderOptions: {
        less: {
          lessOptions: {
            // 在这里添加自定义的Less配置
          },
        },
      },
      postcss: {
        plugins: [
          poscssPresetEnv(),
        ],
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    // base: '/ngp-cloud/',
    base: './',
    server: {
      host: "0.0.0.0",
      hmr: true,
      proxy: {
        [env.VITE_APP_API]: {
          target: HOST,	//实际请求地址
          changeOrigin: true,
          // rewrite: (path) => {
          //   const prefixPath = path
          //   console.log('[ prefixPath ]', HOST + prefixPath, env.VITE_APP_API)
          //   return prefixPath;
          // }
        }
      }
    },
    build: {
      sourcemap: true,
      rollupOptions: {
        output: {
          manualChunks: (id) => {
            if (id.includes('src/main.js') ||
              id.includes('src/App.vue') ||
              id.includes('src/router')) {
              return 'main';
            }

            // JSON地图数据过大，单独打包
            if (id.includes('/json/') && id.endsWith('.json')) {
              return 'map-data';
            }

            // 第三方库分包
            if (id.includes('node_modules')) {
              // Vue核心库
              if ((id.includes('/vue/') || id.includes('/vue@') ||
                id.includes('/vue-router/') || id.includes('/vue-router@') ||
                id.includes('/pinia/') || id.includes('/pinia@')) &&
                !id.includes('ant-design-vue')) {
                return 'vue-vendor';
              }

              // lodash-es
              if (id.includes('lodash-es')) {
                return 'lodash-vendor';
              }

              // ant-design-vue
              if (id.includes('ant-design-vue') || id.includes('@ant-design/icons-vue')) {
                return 'antd-vendor';
              }

              // ezuikit-js 萤石云库
              if (id.includes('ezuikit-js')) {
                return 'ezuikit-js-vendor';
              }

              // echarts
              if (id.includes('echarts')) {
                return 'echarts-vendor';
              }

              // html2canvas
              if (id.includes('html2canvas')) {
                return 'html2canvas-vendor';
              }

              // jspdf
              if (id.includes('jspdf')) {
                return 'jspdf-vendor';
              }

              // 常用工具库
              if (id.includes('axios') ||
                id.includes('dayjs') ||
                id.includes('moment') ||
                id.includes('lodash') ||
                id.includes('crypto-js')) {
                return 'utils-vendor';
              }

              // 其他第三方库
              return 'vendors';
            }
          },

          // 文件名配置
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
        }
      },
      // chunk大小警告限制
      chunkSizeWarningLimit: 1000,
      // 启用CSS拆分
      cssCodeSplit: true,
    },
  }

})
